<?php
namespace app\index\controller;
use think\Controller;

use think\Db;
use think\facade\Log;
use app\service\orderService;
use printing\printDemo;
use app\service\apiService;
use think\Queue;
//error_reporting(0);
class Callback extends Controller{
    
    public function getuser(){
        $api = new apiService();
        //获取当前用户支付宝ID
        $code = request()->get('auth_code');
        $oauthtoken = $api->oauthToken($code);
        if(property_exists($oauthtoken,'sub_msg')){
            return json(['info' => $oauthtoken->sub_msg]);
        }
        
        session('user_id',$oauthtoken->user_id);
        $url=session("url");
        $this->redirect($url);
        die;    
    }
    
    //停车收款回调
    public function gatepayNotice(){
        $path=dir(getcwd())->path.'/pay/gatepay/'.date('Ymd');
        if (! file_exists ( $path )) {
            mkdir ( "$path", 0777, true );
        }
        $address = $path."/".date('His').rand(100000,999999).'.txt';
        file_put_contents($address,file_get_contents("php://input"),FILE_APPEND);
        parse_str(file_get_contents($address),$result);//读取文本并变成数组
        if($result['trade_status'] == 'TRADE_SUCCESS'){
             $billinfo=Db::table("parkgatebill")->where('trade_no',$result['trade_no'])->find();
            if(!empty($billinfo)){
                if($billinfo["order_status"]=="0"){
                     $res=Db::table("parkgatebill")->where("id",$billinfo["id"])->update(["order_status"=>"SUCCESS","pay_type"=>"1","pay_time"=>$result['gmt_payment']]);
                    if($res){
                        $info=Db::table("parkgatebill")->where("id",$billinfo["id"])->find();
                        $info["pay_time"]=strtotime($info["pay_time"]);
                        $info["buyer_logon_id"]=$result['buyer_logon_id'];
                        
                        Db::table("parkgatebillorder")->insert($info);

                        $gateinfo=Db::table("parking_gatepay")->where("id",$info["gateid"])->find();

    					
    					if(!empty($gateinfo["terminal_yly"])){
    					    $pay_type="支付宝";
    					    $printing = (new printDemo())->gatepayprinting($gateinfo["terminal_yly"],$info["parkingName"],$gateinfo["gateName"],$pay_type,$info["pay_money"],date("Y-m-d H:i:s"),$info["remark"]);


    					}

                        if(!empty($gateinfo["voice_id"])){
    						$voice_id=$gateinfo["voice_id"];
    						$price=$info['pay_money']*100;
    						$url="http://cloudspeaker.smartlinkall.com/add.php?id=".$voice_id."&uid=API_ZZKJ&token=110921791234&price=".$price."&pt=1";
    						$res=file_get_contents($url);
    						//Log::write($url,"喇叭");
    					}
                    }
                     
                }
                
             }
        }
    }

    public function gatewxnotice(){
        $path=dir(getcwd())->path.'/pay/gatepaywx/'.date('Ymd');
        if (! file_exists ( $path )) {
            mkdir ( "$path", 0777, true );
        }
        $address = $path."/".date('His').rand(100000,999999).'.txt';
        file_put_contents($address,file_get_contents("php://input"),FILE_APPEND);//将数据读入文本


        $xmldata = file_get_contents($address);
        //将xml数据转化为数组
        $result = json_decode(json_encode(simplexml_load_string($xmldata, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){

            $billinfo=Db::table("parkgatebill")->where('trade_no',$result['out_trade_no'])->find();
            if(!empty($billinfo)){
                if($billinfo["order_status"]=="0"){
                    $res=Db::table("parkgatebill")->where("id",$billinfo["id"])->update(["order_status"=>"SUCCESS","pay_type"=>"2","pay_time"=>$result['time_end']]);
                    if($res){
                        $info=Db::table("parkgatebill")->where("id",$billinfo["id"])->find();
                        $info["pay_time"]=strtotime($info["pay_time"]);
                        $info["buyer_logon_id"]=$result['openid'];

                        Db::table("parkgatebillorder")->insert($info);

                        $gateinfo=Db::table("parking_gatepay")->where("id",$info["gateid"])->find();


                        if(!empty($gateinfo["terminal_yly"])){
                            $pay_type="微信";
                            $printing = (new printDemo())->gatepayprinting($gateinfo["terminal_yly"],$info["parkingName"],$gateinfo["gateName"],$pay_type,$info["pay_money"],date("Y-m-d H:i:s"),$info["remark"]);


                        }

                        if(!empty($gateinfo["voice_id"])){
                            $voice_id=$gateinfo["voice_id"];
                            $price=$info['pay_money']*100;
                            $url="http://cloudspeaker.smartlinkall.com/add.php?id=".$voice_id."&uid=API_ZZKJ&token=110921791234&price=".$price."&pt=2";
                            $res=file_get_contents($url);
                            //Log::write($url,"喇叭");
                        }
                    }

                }

            }
        }
    }

    public function test(){
        echo 2;die;
        $path=dir(getcwd())->path.'/pay/alinotice/'.date('Ymd');
        if (! file_exists ( $path )) {
            mkdir ( "$path", 0777, true );
        }
        $address = $path."/194437880882.txt";
        //file_put_contents($address,file_get_contents("php://input"),FILE_APPEND);
        parse_str(file_get_contents($address),$result);//读取文本并变成数组
        echo "<pre>";
        var_dump($result);die;
        if($result['trade_status'] == 'TRADE_SUCCESS'){
            $info=Db::table("car_order_pay")->where('tradeno',$result['trade_no'])->find();
            var_dump($info);
            if(!empty($info)){
                if($info["payStatus"]=="0"){
                    $res=Db::table("car_order_pay")->where("id",$info["id"])->update(["payStatus"=>"SUCCESS","payType"=>"1","paytime"=>$result['gmt_payment']]);
                    if($res){
                        $orderinfo["parkingNo"]=$info["parkingNo"];
                        $orderinfo["parkingName"]=$info["parkingName"];
                        $orderinfo["clientNo"]=$info["clientNo"];
                        $orderinfo["outParkingOrderNo"]=$info["outParkingOrderNo"];
                        $orderinfo["amountRec"]=$info["amountRec"];
                        $orderinfo["amountDue"]=$info["amountDue"];
                        $orderinfo["parkingStartTime"]=$info["parkingStartTime"];
                        $orderinfo["user_id"]=$info["user_id"];
                        $orderinfo["paytime"]=date("YmdHis",strtotime($result['gmt_payment']));
                        $orderinfo["carPlateNo"]=$info["carPlateNo"];
                        $orderinfo["reqNo"]=date("YmdHis")."-".rand(100000,999999);
                        $orderinfo["parkingTime"]=$info["parkingTime"];
                        $orderinfo["tradeno"]=$info["tradeno"];
                        $orderinfo["out_trade_no"]=$info["out_trade_no"];
                        $orderinfo["outChannelNo"]=$info["outChannelNo"];
                        $orderinfo["subject"]=$info["subject"];
                        $orderinfo["payType"]="1";
                        $orderinfo["parkingEndTime"]=date("YmdHis");
                        $order_id=Db::table("car_order")->insertGetId($orderinfo);
                        $data["order_id"]=$order_id;
                        $this->fsockopen('http://www.aliwgzf.com/index/callback/orderpaymsg',$data);
                    }
                }
            }
        }
    }
    public function alinotice(){
        $path=dir(getcwd())->path.'/pay/alinotice/'.date('Ymd');
        if (! file_exists ( $path )) {
            mkdir ( "$path", 0777, true );
        }
        $address = $path."/".date('His').rand(100000,999999).'.txt';
        file_put_contents($address,file_get_contents("php://input"),FILE_APPEND);
        parse_str(file_get_contents($address),$result);//读取文本并变成数组
        
        if($result['trade_status'] == 'TRADE_SUCCESS'){
            $info=Db::table("car_order_pay")->where('tradeno',$result['trade_no'])->find();
            if(!empty($info)){
                if($info["payStatus"]=="0"){
                    $res=Db::table("car_order_pay")->where("id",$info["id"])->update(["payStatus"=>"SUCCESS","payType"=>"1","paytime"=>$result['gmt_payment']]);
                    if($res){
                        $orderinfo["parkingNo"]=$info["parkingNo"];
                        $orderinfo["parkingName"]=$info["parkingName"];
                        $orderinfo["clientNo"]=$info["clientNo"];
                        $orderinfo["outParkingOrderNo"]=$info["outParkingOrderNo"];
                        $orderinfo["amountRec"]=$info["amountRec"];
                        $orderinfo["amountDue"]=$info["amountDue"];
                        $orderinfo["parkingStartTime"]=$info["parkingStartTime"];
                        $orderinfo["user_id"]=$info["user_id"];
                        $orderinfo["paytime"]=date("YmdHis",strtotime($result['gmt_payment']));
                        $orderinfo["carPlateNo"]=$info["carPlateNo"];
                        $orderinfo["reqNo"]=date("YmdHis")."-".rand(100000,999999);
                        $orderinfo["parkingTime"]=$info["parkingTime"];
                        $orderinfo["tradeno"]=$info["tradeno"];
                        $orderinfo["out_trade_no"]=$info["out_trade_no"];
                        $orderinfo["outChannelNo"]=$info["outChannelNo"];
                        $orderinfo["subject"]=$info["subject"];
                        $orderinfo["payType"]="1";
                        $orderinfo["parkingEndTime"]=date("YmdHis");
                        $order_id=Db::table("car_order")->insertGetId($orderinfo);

                        //查询客户端
                        $clientInfo=(new orderService())->clientInfo($info["parkingNo"],$info["clientNo"]);
                        if(!empty($clientInfo["terminal_yly"])){
                            $pay_type="支付宝";
                            (new printDemo())->carOrder($clientInfo["terminal_yly"],$info["parkingName"],$info["carPlateNo"],$info["parkingStartTime"],date("YmdHis"),ctime($info["parkingTime"]),$info["amountRec"]/100,$pay_type);
                        }


                        $data["order_id"]=$order_id;
                        $this->fsockopen('http://www.aliwgzf.com/index/callback/orderpaymsg',$data);


                    }
                }
            }
        }
    }
    public function aliprenotice(){
        $path=dir(getcwd())->path.'/pay/aliprenotice/'.date('Ymd');
        if (! file_exists ( $path )) {
            mkdir ( "$path", 0777, true );
        }
        $address = $path."/".date('His').rand(100000,999999).'.txt';
        file_put_contents($address,file_get_contents("php://input"),FILE_APPEND);
        parse_str(file_get_contents($address),$result);//读取文本并变成数组
        
        if($result['trade_status'] == 'TRADE_SUCCESS'){
            $info=Db::table("car_order_pay")->where('tradeno',$result['trade_no'])->find();
            if(!empty($info)){
                if($info["payStatus"]=="0"){
                    $res=Db::table("car_order_pay")->where("id",$info["id"])->update(["payStatus"=>"SUCCESS","payType"=>"1","paytime"=>$result['gmt_payment']]);
                    if($res){
                        $orderinfo["parkingNo"]=$info["parkingNo"];
                        $orderinfo["parkingName"]=$info["parkingName"];
                        $orderinfo["clientNo"]=$info["clientNo"];
                        $orderinfo["outParkingOrderNo"]=$info["outParkingOrderNo"];
                        $orderinfo["amountRec"]=$info["amountRec"];
                        $orderinfo["amountDue"]=$info["amountDue"];
                        $orderinfo["parkingStartTime"]=$info["parkingStartTime"];
                        $orderinfo["user_id"]=$info["user_id"];
                        $orderinfo["paytime"]=date("YmdHis",strtotime($result['gmt_payment']));
                        $orderinfo["carPlateNo"]=$info["carPlateNo"];
                        $orderinfo["reqNo"]=date("YmdHis")."-".rand(100000,999999);
                        $orderinfo["parkingTime"]=$info["parkingTime"];
                        $orderinfo["tradeno"]=$info["tradeno"];
                        $orderinfo["out_trade_no"]=$info["out_trade_no"];
                        $orderinfo["outChannelNo"]=$info["outChannelNo"];
                        $orderinfo["subject"]=$info["subject"];
                        $orderinfo["payType"]="8";
                        $orderinfo["parkingEndTime"]=date("YmdHis");
                        $order_id=Db::table("car_order")->insertGetId($orderinfo);
                        $data["order_id"]=$order_id;
                        $this->fsockopen('http://www.aliwgzf.com/index/callback/orderprepaymsg',$data);
                    }
                }
            }
        }
    }
    
    public function wxnotice(){
        $path=dir(getcwd())->path.'/pay/wxnotice/'.date('Ymd');
        if (! file_exists ( $path )) {
            mkdir ( "$path", 0777, true );
        }
        $address = $path."/".date('His').rand(100000,999999).'.txt';
        file_put_contents($address,file_get_contents("php://input"),FILE_APPEND);//将数据读入文本
        
        
        $xmldata = file_get_contents($address);
        //将xml数据转化为数组
        $result = json_decode(json_encode(simplexml_load_string($xmldata, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
            $info=Db::table("car_order_pay")->where('tradeno',$result['out_trade_no'])->find();
            if(!empty($info)){
                if($info["payStatus"]=="0"){
                    $res=Db::table("car_order_pay")->where("id",$info["id"])->update(["payStatus"=>"SUCCESS","payType"=>"2","paytime"=>$result['time_end']]);
                    if($res){
                        $orderinfo["parkingNo"]=$info["parkingNo"];
                        $orderinfo["parkingName"]=$info["parkingName"];
                        $orderinfo["clientNo"]=$info["clientNo"];
                        $orderinfo["outParkingOrderNo"]=$info["outParkingOrderNo"];
                        $orderinfo["amountRec"]=$info["amountRec"];
                        $orderinfo["amountDue"]=$info["amountDue"];
                        $orderinfo["parkingStartTime"]=$info["parkingStartTime"];
                        $orderinfo["user_id"]=$info["user_id"];
                        $orderinfo["paytime"]=$result['time_end'];
                        $orderinfo["carPlateNo"]=$info["carPlateNo"];
                        $orderinfo["reqNo"]=date("YmdHis")."-".rand(100000,999999);
                        $orderinfo["parkingTime"]=$info["parkingTime"];
                        $orderinfo["tradeno"]=$info["tradeno"];
                        $orderinfo["out_trade_no"]=$info["out_trade_no"];
                        $orderinfo["outChannelNo"]=$info["outChannelNo"];
                        $orderinfo["subject"]=$info["subject"];
                        $orderinfo["payType"]="2";
                        $orderinfo["parkingEndTime"]=date("YmdHis");
                        $order_id=Db::table("car_order")->insertGetId($orderinfo);
                        $data["order_id"]=$order_id;
                        $this->fsockopen('http://www.aliwgzf.com/index/callback/orderpaymsg',$data);

                        //查询客户端
                        $clientInfo=(new orderService())->clientInfo($info["parkingNo"],$info["clientNo"]);
                        if(!empty($clientInfo["terminal_yly"])){
                            $pay_type="微信";
                            (new printDemo())->carOrder($clientInfo["terminal_yly"],$info["parkingName"],$info["carPlateNo"],$info["parkingStartTime"],date("YmdHis"),ctime($info["parkingTime"]),$info["amountRec"]/100,$pay_type);
                        }
                    }
                }
            }
        }
    }
    
    public function wxprenotice(){
        $path=dir(getcwd())->path.'/pay/wxprenotice/'.date('Ymd');
        if (! file_exists ( $path )) {
            mkdir ( "$path", 0777, true );
        }
        $address = $path."/".date('His').rand(100000,999999).'.txt';
        file_put_contents($address,file_get_contents("php://input"),FILE_APPEND);//将数据读入文本
        
        
        $xmldata = file_get_contents($address);
        //将xml数据转化为数组
        $result = json_decode(json_encode(simplexml_load_string($xmldata, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
            $info=Db::table("car_order_pay")->where('tradeno',$result['out_trade_no'])->find();
            if(!empty($info)){
                if($info["payStatus"]=="0"){
                    $res=Db::table("car_order_pay")->where("id",$info["id"])->update(["payStatus"=>"SUCCESS","payType"=>"2","paytime"=>$result['time_end']]);
                    if($res){
                        $orderinfo["parkingNo"]=$info["parkingNo"];
                        $orderinfo["parkingName"]=$info["parkingName"];
                        $orderinfo["clientNo"]=$info["clientNo"];
                        $orderinfo["outParkingOrderNo"]=$info["outParkingOrderNo"];
                        $orderinfo["amountRec"]=$info["amountRec"];
                        $orderinfo["amountDue"]=$info["amountDue"];
                        $orderinfo["parkingStartTime"]=$info["parkingStartTime"];
                        $orderinfo["user_id"]=$info["user_id"];
                        $orderinfo["paytime"]=$result['time_end'];
                        $orderinfo["carPlateNo"]=$info["carPlateNo"];
                        $orderinfo["reqNo"]=date("YmdHis")."-".rand(100000,999999);
                        $orderinfo["parkingTime"]=$info["parkingTime"];
                        $orderinfo["tradeno"]=$info["tradeno"];
                        $orderinfo["out_trade_no"]=$info["out_trade_no"];
                        $orderinfo["outChannelNo"]=$info["outChannelNo"];
                        $orderinfo["subject"]=$info["subject"];
                        $orderinfo["payType"]="9";
                        $order_id=Db::table("car_order")->insertGetId($orderinfo);
                        $data["order_id"]=$order_id;
                        $this->fsockopen('http://www.aliwgzf.com/index/callback/orderprepaymsg',$data);
                    }
                }
            }
        }
    }
    
    public function orderprepaymsg(){
        $param=request()->post();
        $orderinfo=Db::table("car_order")->where("order_id",$param["order_id"])->find();
        if(empty($orderinfo)){
            return "订单信息不存在";
        }
        $response["bizCode"]="B1013";
        $response["parkingNo"]=$orderinfo["parkingNo"];
        $response["parkingName"]=$orderinfo["parkingName"];
        $response["clientNo"]=$orderinfo["clientNo"];
        $response["reqNo"]=$orderinfo["reqNo"];
        $response["version"]="V1.0";
        $response["parkingStartTime"]=$orderinfo["parkingStartTime"];
        $response["carPlateNo"]=$orderinfo["carPlateNo"];
        
        $response["outParkingOrderNo"]=$orderinfo["outParkingOrderNo"];
        $response["tradeNo"]=$orderinfo["tradeno"];
        $orderType="prePay";
        $response["orderType"]=$orderType;
        
        $response["payStatus"]="SUCCESS";
        $response["payDateTime"]=date("YmdHis",strtotime($orderinfo["paytime"]));;
        $response["amountDue"]=$orderinfo["amountDue"];
        $response["amountRec"]=$orderinfo["amountRec"];
        
        $parkinginfo=Db::table("parkinglotinfo")->where("parkingNo",$orderinfo["parkingNo"])->find();
        $parkingKey=$parkinginfo["parkingKey"];
        $response["sign"]=$this->MakeSign($response,$parkingKey);
        $result=$this->jsondata($response);
        //return $result;
        $client=new \swoole_client(SWOOLE_SOCK_TCP);
        if(!$client->Connect("47.106.184.188",9500,0.5)){
            echo "errCode:".$client->errCode."\r\n";
            die("connect failed\r\n");
        }
        
        $client->send($result."\r\n");
        //从服务端接收信息
        $data=$client->recv();
        if(!$data){
           
            die("recv failed \r\n");
        }
    }
    public function orderpaymsg(){
        $param=request()->post();
        $orderinfo=Db::table("car_order")->where("order_id",$param["order_id"])->find();
        if(empty($orderinfo)){
            return "订单信息不存在";
        }
        $response["bizCode"]="B1013";
        $response["parkingNo"]=$orderinfo["parkingNo"];
        $response["parkingName"]=$orderinfo["parkingName"];
        $response["clientNo"]=$orderinfo["clientNo"];
        $response["reqNo"]=$orderinfo["reqNo"];
        $response["version"]="V1.0";
        $response["parkingStartTime"]=$orderinfo["parkingStartTime"];
        $response["carPlateNo"]=$orderinfo["carPlateNo"];
        
        $response["outParkingOrderNo"]=$orderinfo["outParkingOrderNo"];
        $response["tradeNo"]=$orderinfo["tradeno"];
        $orderType="outPay";
        $response["orderType"]=$orderType;
        $response["outChannelNo"]=$orderinfo["outChannelNo"];;
        $response["payStatus"]="SUCCESS";
        $response["payDateTime"]=date("YmdHis",strtotime($orderinfo["paytime"]));;
        $response["amountDue"]=$orderinfo["amountDue"];
        $response["amountRec"]=$orderinfo["amountRec"];
        
        $parkinginfo=Db::table("parkinglotinfo")->where("parkingNo",$orderinfo["parkingNo"])->find();
        $parkingKey=$parkinginfo["parkingKey"];
        $response["sign"]=$this->MakeSign($response,$parkingKey);
        $result=$this->jsondata($response);
        //return $result;
        $client=new \swoole_client(SWOOLE_SOCK_TCP);
        if(!$client->Connect("47.106.184.188",9500,0.5)){
            echo "errCode:".$client->errCode."\r\n";
            die("connect failed\r\n");
        }
        
        $client->send($result."\r\n");
        //从服务端接收信息
        $data=$client->recv();
        if(!$data){
           
            die("recv failed \r\n");
        }
    }
    public function orderpaymsg2(){
        $param=request()->post();
        //$param["order_id"]=240;
        $orderinfo=Db::table("car_order")->where("order_id",$param["order_id"])->find();
        //Log::write($orderinfo,"orderpaymsg2");
        if(empty($orderinfo)){
            return "订单信息不存在";
        }
        $response["bizCode"]="B1013";
        $response["parkingNo"]=$orderinfo["parkingNo"];
        $response["parkingName"]=$orderinfo["parkingName"];
        $response["clientNo"]=$orderinfo["clientNo"];
        $response["reqNo"]=$orderinfo["reqNo"];
        $response["version"]="V1.0";
        $response["parkingStartTime"]=$orderinfo["parkingStartTime"];
        $response["carPlateNo"]=$orderinfo["carPlateNo"];
        
        $response["outParkingOrderNo"]=$orderinfo["outParkingOrderNo"];
        $response["tradeNo"]=$orderinfo["tradeno"];
        $orderType="outPay";
        $response["orderType"]=$orderType;
        $response["outChannelNo"]=$orderinfo["outChannelNo"];;
        $response["payStatus"]="SUCCESS";
        $response["payDateTime"]=date("YmdHis",strtotime($orderinfo["paytime"]));;
        $response["amountDue"]=$orderinfo["amountDue"];
        $response["amountRec"]=$orderinfo["amountRec"];
        
        $parkinginfo=Db::table("parkinglotinfo")->where("parkingNo",$orderinfo["parkingNo"])->find();
        $parkingKey=$parkinginfo["parkingKey"];
        $response["sign"]=$this->MakeSign($response,$parkingKey);
        $result=$this->jsondata($response);
        //Log::write($result,"orderpayresult");
        //return $result;
        $client=new \swoole_client(SWOOLE_SOCK_TCP);
        if(!$client->Connect("47.106.184.188",9501,20)){
            echo "errCode:".$client->errCode."\r\n";
            die("connect failed\r\n");
        }
        
        $client->send($result."\r\n");
        //从服务端接收信息
        $data=$client->recv();
        if(!$data){
           
            die("recv failed \r\n");
        }
    }
    
    public function fsockopen($url,$post_data=array(),$cookie=array()){
        $url_arr = parse_url($url);
        $port = isset($url_arr['port'])?$url_arr['port']:80;
        if($url_arr['scheme'] == 'https'){
            $url_arr['host'] = 'ssl://'.$url_arr['host'];
        }
        $fp = fsockopen($url_arr['host'],$port,$errno,$errstr,30);
        if(!$fp) return false;
        $getPath = isset($url_arr['path'])?$url_arr['path']:'/index.php';
        $getPath .= isset($url_arr['query'])?'?'.$url_arr['query']:'';
        $method = 'GET';  //默认get方式
        if(!empty($post_data)) $method = 'POST';
        $header = "$method  $getPath  HTTP/1.1\r\n";
        $header .= "Host: ".$url_arr['host']."\r\n";
        if(!empty($cookie)){  //传递cookie信息
            $_cookie = strval(NULL);
            foreach($cookie AS $k=>$v){
                $_cookie .= $k."=".$v.";";
            }
            $cookie_str = "Cookie:".base64_encode($_cookie)."\r\n";
            $header .= $cookie_str;
        }
        if(!empty($post_data)){  //传递post数据
            $_post = array();
            foreach($post_data AS $_k=>$_v){
                $_post[] = $_k."=".urlencode($_v);
            }
            $_post = implode('&', $_post);
            $post_str = "Content-Type:application/x-www-form-urlencoded; charset=UTF-8\r\n";
            $post_str .= "Content-Length: ".strlen($_post)."\r\n";  //数据长度
            $post_str .= "Connection:Close\r\n\r\n";
            $post_str .= $_post;  //传递post数据
            $header .= $post_str;
        }else{
            $header .= "Connection:Close\r\n\r\n";
        }
        fwrite($fp, $header);
        //echo fread($fp,1024);
        usleep(1000); // 这一句也是关键，如果没有这延时，可能在nginx服务器上就无法执行成功
        fclose($fp);
        return true;
    }
    
    
    
    private function jsondata($arr){
        $str='{';
        foreach($arr as $key =>$value){
            $str=$str.'"'.$key.'":"'.$value.'",';
        }
        $str = trim($str, ",");
        $str=$str.'}';
        return $str;
    }
    private function MakeSign($arr,$parkingKey){
        //签名步骤一：按字典序排序参数
        ksort($arr);
        $string = $this->ToUrlParams($arr);
        //签名步骤二：在string后加入KEY
        $string = $string . "&key=" . $parkingKey;
        //签名步骤三：MD5加密
        $string = md5($string);
        //签名步骤四：所有字符转为大写
        $result = strtoupper($string);
        return $result;
    }
    
    //格式化参数格式化成url参数(str)
    private function ToUrlParams($value){
        $buff = "";
        foreach($value as $k => $v){
            if($k != "sign" && $v != "" && !is_array($v)){
                $buff .= strtolower($k) . "=" . $v . "&";
            }
        }
        $buff = trim($buff, "&");
        return $buff;
    }
}
